package com.yunda.vedio_library.util;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Environment;
import android.text.TextUtils;

import androidx.appcompat.app.AppCompatActivity;

import com.yunda.vedio_library.PlayAudioActivity;
import com.yunda.vedio_library.SimplePlayer;
import com.yunda.vedio_library.imp.CompressListener;

import java.lang.ref.WeakReference;

import io.microshow.rxffmpeg.RxFFmpegCommandList;
import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;
import io.reactivex.disposables.CompositeDisposable;

/**
 * copyright (C), 2022, 运达科技有限公司
 * fileName YdVedio
 *
 * @author 王玺权
 * date 2022-05-20 15:20
 * description 视频播放帮助类
 * history
 */
public enum YdVedio {
    /**
     * 单例
     */
    INSTANCE;
    private MyRxFFmpegSubscriber myRxFFmpegSubscriber;
    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    private long startTime;//记录开始时间
    private long endTime;//记录结束时间

    private ProgressDialog mProgressDialog;

    private CompressListener mCompressListener;
    private String compressInputUrl;
    private String compressOutputUrl;
    private AppCompatActivity compressActivity;
    /**
     * 播放视频本地与网络
     * @param mActivity 传入 activity
     * @param title 视频标题
     * @param url 视频url 全路径
     */
    public void playVedio(Activity mActivity,String title,String url){
        Intent intent=new Intent();
        intent.putExtra("title",title);
        intent.putExtra("url",url);
        intent.setClass(mActivity, SimplePlayer.class);
        mActivity.startActivity(intent);
    }

    /**
     * 播放视频本地
     * @param mActivity 传入 activity
     * @param url 视频url 全路径
     */
    public void playAudio(Activity mActivity,String url){

        Intent intent=new Intent();
        intent.putExtra("audioPath",url);
        intent.setClass(mActivity, PlayAudioActivity.class);
        mActivity.startActivity(intent);
    }

    /**
     * 压缩视频
     */
    public YdVedio compressVedio(AppCompatActivity mActivity,String inputUrl,String outputUrl){
        this.compressActivity=mActivity;
        this.compressInputUrl=inputUrl;
        this.compressOutputUrl=outputUrl;
        runFFmpegRxJava(mActivity,compressInputUrl,compressOutputUrl);
        return this;
    }


    /**
     * rxjava方式调用
     */
    private void runFFmpegRxJava(AppCompatActivity mActivity,String inputUrl,String outputUrl) {
        openProgressDialog(mActivity);

        String[] commands = getBoxblur(inputUrl,outputUrl);

        myRxFFmpegSubscriber = new MyRxFFmpegSubscriber(mActivity);

        //开始执行FFmpeg命令
        RxFFmpegInvoke.getInstance()
                .runCommandRxJava(commands)
                .subscribe(myRxFFmpegSubscriber);

    }
    private void openProgressDialog(AppCompatActivity mActivity) {
        //统计开始时间
        startTime = System.nanoTime();
        mProgressDialog = Utils.openProgressDialog(mActivity);
    }
    // 这里设为静态内部类，防止内存泄露
    public  class MyRxFFmpegSubscriber extends RxFFmpegSubscriber {

        private WeakReference<? extends AppCompatActivity> mWeakReference;

        public MyRxFFmpegSubscriber(AppCompatActivity mainActivity) {
            mWeakReference = new WeakReference<>(mainActivity);
        }

        @Override
        public void onFinish() {
            final AppCompatActivity mHomeFragment = mWeakReference.get();
            if (mHomeFragment != null) {
//                cancelProgressDialog(compressActivity,"处理成功");
                if (mProgressDialog != null) {
                    mProgressDialog.cancel();
                }
                mCompressListener.compressResult(true,compressOutputUrl,"处理成功");
            }
        }

        @Override
        public void onProgress(int progress, long progressTime) {
            final AppCompatActivity mHomeFragment = mWeakReference.get();
            if (mHomeFragment != null) {
                //progressTime 可以在结合视频总时长去计算合适的进度值
                setProgressDialog(progress, progressTime);
            }
        }

        @Override
        public void onCancel() {
            final AppCompatActivity mHomeFragment = mWeakReference.get();
            if (mHomeFragment != null) {
                cancelProgressDialog(compressActivity,"已取消");
            }else {
                mCompressListener.compressResult(false,"","已取消");
            }
        }

        @Override
        public void onError(String message) {
            final AppCompatActivity mHomeFragment = mWeakReference.get();
            if (mHomeFragment != null) {
                cancelProgressDialog(compressActivity,"出错了 onError：" + message);
                mCompressListener.compressResult(false,"","出错了 onError：" + message);
            }
        }
    }


    /**
     * 压缩执行参数
     * @param inputUrl 压缩视频地址
     * @param outputUrl 输出视频地址
     * @return
     */
    public  String[] getBoxblur(String inputUrl,String outputUrl) {
        RxFFmpegCommandList cmdlist = new RxFFmpegCommandList();
        cmdlist.append("-i");
        cmdlist.append(inputUrl);
        cmdlist.append("-vf");
        cmdlist.append("boxblur=5:1");
        cmdlist.append("-preset");
        cmdlist.append("superfast");
        cmdlist.append(outputUrl);
        return cmdlist.build();
    }

    /**
     * 设置进度条
     */
    private  void setProgressDialog(int progress, long progressTime) {
        if (mProgressDialog != null) {
            mProgressDialog.setProgress(progress);
            //progressTime 可以在结合视频总时长去计算合适的进度值
            mProgressDialog.setMessage("已处理progressTime=" + (double) progressTime / 1000000 + "秒");
        }
    }

    private void showDialog(AppCompatActivity mActivity,String message) {
        //统计结束时间
        endTime = System.nanoTime();
        Utils.showDialog(mActivity, message, Utils.convertUsToTime((endTime - startTime) / 1000, false));
//        StatService.onEventDuration(MainActivity.this, "RunFFmpegCommand", binding.editText.getText().toString(), (endTime - startTime) / (1000 * 1000));
    }

    /**
     * 取消进度条
     *
     * @param dialogTitle Title
     */
    private  void cancelProgressDialog(AppCompatActivity mActivity,String dialogTitle) {
        if (mProgressDialog != null) {
            mProgressDialog.cancel();
        }
        if (!TextUtils.isEmpty(dialogTitle)) {
            showDialog(mActivity,dialogTitle);
        }
    }
    public void setCompressListener(CompressListener compressListener){
        this.mCompressListener=compressListener;
    }
    public void compressDestory(){
        if (myRxFFmpegSubscriber != null) {
            myRxFFmpegSubscriber.dispose();
        }
        mCompositeDisposable.clear();
    }
}
